﻿using System;
using System.Data.Entity;
using iHouse.Infrastructure;
using iHouse.Model.Cache;
using iHouse.Model.Repository.Interface;
using Microsoft.Practices.Unity;

namespace iHouse.Model.Repository
{
    public abstract class BaseRepository<T, TEntity> : IBaseRepository<TEntity> where T : DbContext
    {
        public BaseRepository()
        {
            //DataContextProvider.RegisterDataContext<T>(ContextKey, ConnectionString);
        }

        [Dependency]
        public virtual IDataContextProvider DataContextProvider
        {
            get
            {
                return _provider;
            }
            set
            {
                if (value != null)
                {
                    _provider = value;
                    _provider.RegisterDataContext<T>(ContextKey, ConnectionString);
                }
            }
        }
        private IDataContextProvider _provider;

        protected abstract string ContextKey { get; }

        public virtual string ConnectionString
        {
            get
            {
                return string.Empty;
            }
        }

        protected virtual T CurrentDataContext
        {
            get
            {
                return DataContextProvider.GetDataContext<T>(ContextKey);
            }
        }

        protected virtual PaginationList<TEntity> GetDataByCategory(int categoryID, int pageIndex, int pageSize)
        {
            return null;
        }

        protected virtual PaginationList<TEntity> GetData(PagingCriteria criteria)
        {
            return null;
        }

        #region IBaseRepository<TEntity> Members

        public PaginationList<TEntity> FindEntitiesByCategory(int categoryID, int pageIndex, int pageSize)
        {
            Func<PaginationList<TEntity>> _findThunk = () => GetDataByCategory(categoryID, pageIndex, pageSize);

            return _findThunk();
        }

        public PaginationList<TEntity> FindEntities(PagingCriteria criteria)
        {
            Func<PaginationList<TEntity>> _findThunk = () => GetData(criteria);

            return _findThunk();
        }

        #endregion
    }
}
